var app = getApp();
function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}
function wxPromisify(fn) {
  return function (obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function (res) {
        resolve(res)
      }

      obj.fail = function (res) {
        reject(res)
      }

      fn(obj)
    })
  }
}

//验证是否是手机号码
function vailPhone(number) {
  let flag = false;
  let myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
  if (number.length != 11) {
    flag = flag;
  } else if (!myreg.test(number)) {
    flag = flag;
  } else {
    flag = true;
  }
  return flag;
}

//授权验证
function authori(url) {
  // 查看是否授权
  wx.getSetting({
    success: function (res) {
      if (!res.authSetting['scope.userInfo']) {// 未授权
        var s = "";
        if (url.path) {//url参数判断
          if (JSON.stringify(url.query) != "{}") {
            let query = url.query;
            s = JSON.stringify(query)
            url = url.path
          } else {
            url = url.path;
          }
        } else {
          url = "/pages/index/index"
        }
        wx.redirectTo({
          url: "/pages/authori/index?back=" + url + "&query=" + s,
        })
      }
    }
  })
}
//授权验证(登陆规范修改后的)
function isAccredit(cb) {
  let isAccredit = false;
  // 查看是否授权
  wx.getSetting({
    success: function (res) {
      if (res.authSetting['scope.userInfo']) {// 已授权
        isAccredit = true;
      }
      cb(isAccredit);
    }
  })
}

//图片路径拼接
function formatAvater(avater, imgPath) {
  if (avater != null && avater.indexOf("http") == 0) {
    return avater;
  } else {
    return imgPath + avater;
  }
}
//当前时间获取
function getCurrentToday() {
  const date = new Date()
  var year = date.getFullYear();
  var mouths = (date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : (date.getMonth() + 1);
  var day = date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate();
  var hours = date.getHours();
  var Minutes = date.getMinutes();//当前分
  var currentdate = year + "-" + mouths + "-" + day + "\t" + hours + ":" + Minutes;
  return currentdate
}

/**
 * 传入时间后几天
 * param：传入时间：dates:"2018-04-02",later:往后多少天
 */
function dateLater(dates, later) {
  let dateObj = {};
  let show_day = new Array('周日', '周一', '周二', '周三', '周四', '周五', '周六');
  let date = new Date(dates);
  date.setDate(date.getDate() + later);
  let day = date.getDay();
  dateObj.dates = ((date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : date.getMonth() + 1) + "月" + (date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate()) + "日";
  dateObj.newdates = ((date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : date.getMonth() + 1) + "-" + (date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate());
  dateObj.year = date.getFullYear();
  dateObj.month = ((date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : date.getMonth() + 1);
  dateObj.day = (date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate());
  dateObj.week = show_day[day];
  return dateObj;
}
//判断两个时间比较大小
function compareDate(d1, d2) {
  return ((new Date(d1.replace(/-/g, "\/"))) > (new Date(d2.replace(/-/g, "\/"))));
}

//获取默认名片
function getDefaultStaff() {
  var that = this;
  var app = getApp();
  wx.request({
    url: app.globalData.host + '/api/BusinessCard/GetStoreDefaultStaff',
    data: { uid: app.globalData.userInfo.Uid },
    success: function(res) {
      if (res.data.Code == 0){
        app.globalData.userStaff = res.data.Data;
        if (app.aiRecordCallback) {
          app.aiRecordCallback();
        }
      }
    }
  })
}

/**
   * 会员的操作记录actionType = 22 查看商品详情 actionType = 23点击底部导航
   *
   * 参数actionType,actionValue,storeid,uid,staffId
   */
function aiCardActionRecord(actionType, actionValue) {
  var app = getApp();
  if(!app.globalData.userInfo || !app.globalData.userStaff){
    return;
  }
  wx.request({
    url: app.globalData.host + '/api/BusinessCard/AddAiCardAction?staffId=' + app.globalData.userStaff.Id + '&uid=' + app.globalData.userInfo.Uid + '&actionType=' + actionType + '&actionValue=' + encodeURIComponent(actionValue) + '&storeId=' + app.globalData.storeId,
    success: function (res) { console.log("操作记录：" + actionType + actionValue)},
  })
}
//记录产品和商圈停留时间
function recordActionTime(startDate, actionType, typeId) {
  var app = getApp();
  var that = this;
  var endDate = formatTime(new Date());
  var d1 = new Date(startDate);
  var d2 = new Date(endDate);
  var seconds = parseInt(d2 - d1) / 1000
  var data = {
    storeId: app.globalData.storeId,
    staffId: 0,
    actionType: actionType, //会员的操作(5 查看商圈,22 查看产品详情)
    typeId: typeId,         //操作对应的ID (actiontype=5 商圈ID, actiontype=22 产品ID)
    seconds: seconds,        //记录时间秒
    uid: app.globalData.userInfo.Uid
  }
  wx.request({
    url: app.globalData.host + '/api/BusinessCard/AddActionTime',
    data: data,
    success: function (res) { console.log("停留时间：" + seconds)},
  })
}


/**
   * 发送表单id
   * 参数formid
   */
function addFormIdMsg(formid) {
  var app = getApp();
  wx.request({
    url: app.globalData.host + '/api/WeApp/AddFormId?uid=' + app.globalData.userInfo.Uid + '&formId=' + formid,
    success: function (res) {
      if (res.data.Code == 0) {}
    },
  })
}
//获取手机号
function getMobile(e) {
  var app = getApp();
  var that = this;
  wx.login({
    success: function (res) {
      var code = res.code;
      wx.request({
        url: app.globalData.host + '/api/account/getphonenumber?encryptedData=' + encodeURIComponent(e.detail.encryptedData) + '&iv=' + encodeURIComponent(e.detail.iv) + '&storeid=' + app.globalData.storeId + '&storeAppId=' + app.globalData.storeAppId + "&code=" + code,
        success: function (res) {
          if (res.data.Code == 0) {
            app.globalData.userInfo.Mobile = res.data.Data;
            wx.setStorageSync("mobile", res.data.Data)
          }
        },
      })
    }
  })
}
//判断小程序是否未ai小程序
function isAiWeApp(app, callbak) {
  wx.request({
    url: app.globalData.host + '/api/store/IsAiWeApp?storeid=' + app.globalData.storeId + '&storeappid=' + app.globalData.storeAppId,
    success: function (res) {
      if (res.data.Code == 0) {
        console.log("是否是ai小程序，" + res.data.Data.IsAiWeApp)
        callbak(res.data.Data.IsAiWeApp);
      }
    },
  })
}

// 订阅消息弹窗
function subscribe() {
  var app = getApp();
  console.log("消息订阅");
  wx.request({
    url: app.globalData.host + '/api/weapp/GetTemplateId?storeAppId=' + app.globalData.storeAppId,
    success: function (res) {
      console.log('模板Id集合', res.data.Data.tmplIds);
      let tmplIds = res.data.Data.tmplIds;
      let newTemplate = [];
      if (tmplIds.length > 3) {
        for (let i = 0; i < 3; i++) {
          newTemplate.push(tmplIds[i]);
        }
      } else {
        newTemplate = tmplIds;
      }
      console.log("筛选后模板id集合", newTemplate);
      if (newTemplate.length > 0){
        wx.requestSubscribeMessage({
          tmplIds: newTemplate,
          success(res) {
            console.log('订阅成功', res);
          },
          fail(res) {
            console.log('订阅失败', res);
          },
          complete(res) {
            console.log('订阅完成', res);
          }
        })
      } 
    }
  })
}

// 订阅消息兼容判断
function subscribe2() {
  var app = getApp();
  console.log("消息订阅2");
  wx.request({
    url: app.globalData.host + '/api/weapp/GetTemplateId?storeAppId=' + app.globalData.storeAppId,
    success: function (res) {
      console.log('模板Id集合2', res.data.Data.tmplIds);
      let tmplIds = res.data.Data.tmplIds;
      let newTemplate = [];
      if (tmplIds.length > 3) {
        for (let i = 0; i < 3; i++) {
          newTemplate.push(tmplIds[i]);
        }
      } else {
        newTemplate = tmplIds;
      }
      const version = wx.getSystemInfoSync().SDKVersion;
      if (compareVersion(version, '2.8.2') >= 0) {
        if (newTemplate.length > 0) {
          wx.requestSubscribeMessage({
            tmplIds: newTemplate,
            success(res) {
              console.log('订阅成功', res);
            },
            fail(res) {
              console.log('订阅失败', res);
            },
            complete(res) {
              console.log('订阅完成', res);
            }
          })
        }
      } else {
        // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
        wx.showModal({
          title: '提示',
          content: '当前微信版本过低，无法使用订阅消息功能，请升级到最新微信版本后重试。'
        })
      }
    }
  })
}

function compareVersion(v1, v2) {
  v1 = v1.split('.')
  v2 = v2.split('.')
  const len = Math.max(v1.length, v2.length)
  while (v1.length < len) {
    v1.push('0')
  }
  while (v2.length < len) {
    v2.push('0')
  }
  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i])
    const num2 = parseInt(v2[i])

    if (num1 > num2) {
      return 1
    } else if (num1 < num2) {
      return -1
    }
  }
  return 0
}

//跳聊天页
function tapChat(userStaff) {
  console.log('新版聊天');
  var app = getApp();
  var nickname = userStaff.Name;
  var seltoid = userStaff.Uid;
  wx.request({
    url: app.globalData.host + '/api/IM/UserByOpenId?openId=' + app.globalData.userInfo.Uid,
    success: function (res) {
      if (res.data.Code == 0) {
        if (res.data.Data) {
          let fromuid = res.data.Data.Id;
          wx.request({
            url: app.globalData.host + '/api/IM/UserByOpenId?openId=' + seltoid,
            success: function (res2) {
              if (res2.data.Code == 0 && res2.data.Data) {
                let touid = res2.data.Data.Id;
                let chatparam = 'touid=' + touid + '&fromuid=' + fromuid + '&nickname=' + nickname + '&storeid=' + app.globalData.storeId
                console.log(chatparam);
                wx.navigateTo({
                  url: '/pages/h5page/index?url=sessionDetail.html&chatparam=' + encodeURIComponent(chatparam),
                })
              } else {
                wx.showModal({
                  title: '提示',
                  content: res.data.Message,
                  showCancel: false
                })
              }
            }
          })
        }
        aiCardActionRecord(18);
      } else {
        wx.showModal({
          title: '提示',
          content: res.data.Message,
          showCancel: false
        })
      }
    }
  })

}
// 关闭socket连接
function toCloseSocket() {
  wx.closeSocket();
  wx.onSocketClose(function (res) {
    console.log('WebSocket 已关闭！')
  })
}

module.exports = {
  wxPromisify: wxPromisify,
  formatTime: formatTime,
  vailPhone: vailPhone,
  authori: authori,
  formatAvater: formatAvater,
  getCurrentToday: getCurrentToday,
  dateLater: dateLater,
  compareDate: compareDate,
  getDefaultStaff: getDefaultStaff,
  aiCardActionRecord: aiCardActionRecord,
  recordActionTime: recordActionTime,
  addFormIdMsg: addFormIdMsg,
  getMobile: getMobile,
  isAiWeApp: isAiWeApp,
  isAccredit: isAccredit,
  subscribe: subscribe,
  subscribe2: subscribe2,
  tapChat: tapChat,
  toCloseSocket: toCloseSocket
}
